import SignRecord from '@/model/SignRecord'
import { getJWTPayload } from "@/common/utils";
import User from '@/model/User'
import moment from 'dayjs'
import send from '@/config/MailConfig'
import uuid from 'uuid/dist/v4'
import jwt from 'jsonwebtoken'
import { getValue, setValue } from '@/config/RedisConfig';
import config from '@/config/index'
import bcrypt from 'bcrypt'
class UserController {
  constructor() { }
  //签到接口
  async userSign (ctx) {
    //去用户的id
    const obj = await getJWTPayload(ctx.header.authorization)
    //查询上一次的签到记录
    const record = await SignRecord.findByUid(obj.id)
    const user = await User.findOne({ _id: obj.id });
    let result = ''
    let newRecord = {}
    //判断签到逻辑
    if (record !== null) {
      //有历史签到数据
      //用户上一次的签到时间 是否和今天相同，如果相同代表用户已经签到签到
      if (moment(record.created).format('YYYY-MM-DD') === moment().format('YYYY-MM-DD')) {
        ctx.body = {
          msg: '用户已经签到',
          favs: user.favs,
          count: user.count,
          lastSign: record.created,
          code: 500
        }
        return;
      } else {
        //有上一次的签到记录
        let count = user.count;
        let fav = 0;
        //用户上一次的签到时间等于当前时间的前一天
        if (moment(record.created).format('YYYY-MM-DD') === moment().subtract(1, 'days').format('YYYY-MM-DD')) {
          count += 1
          if (count < 5) {
            fav = 5;
          } else if (count >= 5 && count < 15) {
            fav = 10
          } else if (count >= 15 && count < 30) {
            fav = 15
          } else if (count >= 30 && count < 100) {
            fav = 20
          } else if (count >= 100 && count < 365) {
            fav = 30
          } else if (count >= 365) {
            fav = 50
          }
          await User.updateOne({ _id: obj.id }, {

            //user.favs += favs   user.count +=1
            $inc: { favs: fav, count: 1 }
          })
          result = {
            favs: user.favs + fav,
            count: user.count += 1
          }
        } else {
          //用户中断了签到
          fav = 5;
          await User.updateOne({ _id: obj.id }, {
            $set: { count: 1 },
            //user.favs += favs   user.count +=1
            $inc: { favs: fav }
          })

          result = {
            favs: user.favs + fav,
            count: 1
          }
        }

        //更新签到时间
        newRecord = new SignRecord({
          uid: obj.id,
          favs: fav,
        })

        await newRecord.save();
      }
    } else {
      //初次签到数据
      //保存用户的签到数据，签到记录+积分数据 $set 是set ，$inc increate 原数据上直接增加
      await User.updateOne({
        _id: user._id,
      },
        {
          $set: { count: 1 },
          $inc: { favs: 5 }
        })
      //保存用户的签到记录
      newRecord = new SignRecord({
        uid: obj.id,
        favs: 5,
      })

      await newRecord.save();

      result = {
        favs: user.favs + 5,
        count: 1
      }
    }
    ctx.body = {
      code: 200,
      msg: '请求成功',
      ...result,
      lastSign: newRecord.created
    }
  }

  //更新用户基本信息接口
  async updateUserInfo (ctx) {
    const { body } = ctx.request
    const obj = await getJWTPayload(ctx.header.authorization)

    let msg = ''
    // 判断是否改变了邮箱，如果改变了，发送邮件
    const user = await User.findOne({ _id: obj.id });
    if (body.username && body.username !== user.username) {
      //判断用户的新邮箱是否存在与数据库中
      const ck = await User.findOne({ username: body.username })
      if (ck && ck.password) {
        ctx.body = {
          code: 501,
          msg: '邮箱已经注册'
        }
        return
      }
      const key = uuid()
      setValue(key, jwt.sign({ _id: user._id }, config.JWT_SECRET, {
        'expiresIn': '30m'
      }), 1800)
      let res = await send({
        type: 'email',
        data: {
          key: key,
          username: body.username
        },
        code: '',
        expire: moment().add(30, 'minutes').format('YYYY-MM-DD HH:mm:ss'),
        email: user.username,
        user: user.nickname,
      })
      msg = '用户基本信息更新成功，邮箱修改需要邮件确认，请查收邮件'
    }
    const arr = ['username', 'password', 'mobile'];
    arr.map((item) => {
      delete body[item]
    })
    const rs = await User.updateOne({ _id: obj.id }, body)
    if (rs.n === 1 && rs.ok === 1) {
      ctx.body = {
        code: 200,
        msg: msg === '' ? '更新成功' : msg
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '更新失败'
      }
    }
  }


  //更新用户名
  async updateUserName (ctx) {
    const body = ctx.request.query;
    console.log(body)
    if (body.key) {
      const token = await getValue(body.key)
      const obj = await getJWTPayload('Bearer ' + token)
      await User.updateOne({ _id: obj._id }, {
        username: body.username
      })

      ctx.body = {
        code: 200,
        msg: '更新邮箱成功'
      }
    }

  }

  //更新用户名
  async updatePass (ctx) {
    const { body } = ctx.request;
    const obj = await getJWTPayload(ctx.header.authorization)
    console.log('obj: ', obj);
    const user = await User.findOne({ _id: obj.id })
    if (user && user.password) {
      let checkUserPass = false
      if (await bcrypt.compare(body.oldpwd, user.password)) {
        checkUserPass = true
      } else {
        checkUserPass = false;
      }

      if (checkUserPass) {
        const newPass = await bcrypt.hash(body.newpwd, 5)
        await User.updateOne({ _id: obj.id }, { password: newPass })
        ctx.body = {
          code: 200,
          msg: '密码修改成功'
        }
        return
      }

      ctx.body = {
        code: 500,
        msg: '密码修改失败'
      }

    } else {
      ctx.body = {
        code: 401,
        msg: '安全验证失败'
      }
    }

  }
}


export default new UserController